const dayjs = require("dayjs");

const camelToUnderline = function (camelStr) {
    return camelStr.replace(/[A-Z]/g, function (s) {
        return '_' + s.toLowerCase();
    })
};

const ObjToUnderline = function (data) {
    if (data instanceof Array) {
        for (let i = 0; i < data.length; i++) {
            const element = data[i];
            ObjToUnderline(element);
        }
        return data
    } else if (data instanceof Object) {
        var _data = {};
        for (const key in data) {
            const element = data[key];
            _data[camelToUnderline(key)] = element;
        };
        return _data;
    } else {
        return data;
    }
}

const formatObject = function (res) {
    let _data = {};
    for (const key in res) {
        if (res.hasOwnProperty(key)) {
            const _item = res[key];
            var _key = key.replace(/\_(\w)/g, function (all, letter) {
                return letter.toUpperCase();
            });
            if (_key == 'updateTime' || _key == 'createTime' || _key == 'submitTime' || _key == 'scoreTime') {
                _data[_key] = dayjs(_item).valueOf();
            } else {
                _data[_key] = _item;
            }
        }
    };
    return _data;
};

const formatArray = function (res) {
    var data = [];
    for (let i = 0; i < res.length; i++) {
        const element = res[i];
        var _data = formatObject(element);
        data.push(_data);
    };
    return data;
};

module.exports = {
    formatObject,
    formatArray,
    ObjToUnderline
}